package com.panshi.controller.sendEmail;

import com.panshi.sendEmail.SendEmailIdentifyServiceImp;
import com.panshi.vo.UserBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Controller
@Slf4j
@RequestMapping("/send")
public class SendEmailController {

    @Autowired
    private RedisTemplate<String,String> template;

    @Resource
    private SendEmailIdentifyServiceImp sendEmailIdentifyService;

    /**
     * 发送邮箱验证码
     * @param userBean
     * @return
     */
    @PostMapping("/send")
    @ResponseBody
    public Map<Object,Object> send(UserBean userBean){

        Map<Object,Object> map = new HashMap<>();

        String sender="2946221370@qq.com";//发送者
        String receiver=userBean.getEmail();//接收者
        String title="验证码";//标题

        String imageIdentify = template.opsForValue().get("验证码："+userBean.getEmail());
        Long time = template.opsForValue().getOperations().getExpire("验证码："+userBean.getEmail());
        //判断是否发送过验证码，如果发送过则只有该验证码过期后才能再次发送
        if (null!=imageIdentify && !"".equals(imageIdentify)){
            map.put("success",false);
            map.put("message","您的验证码已发送，"+time+"s后再发");
            return map;
        }

        //获取5个随机数
        Random random = new Random();
        String identify = "";
        for (int i = 0; i < 5; i++) {
            int num = random.nextInt(10);
            identify = identify+num;
        }
        template.opsForValue().set("验证码："+userBean.getEmail(),identify);
        //设置有效期TimeUnit.SECONDS时间单位秒（s）
        template.opsForValue().set("验证码："+userBean.getEmail(),identify,90, TimeUnit.SECONDS);

        //发送邮箱
        sendEmailIdentifyService.sendMessage(sender,receiver,title,identify);
        map.put("success",true);
        map.put("message","该验证码90s内有效");

        return map;
    }

}
